



# -*- coding: UTF-8 -*-
import os, sys
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
PKG_PATH = CUR_PATH[0:CUR_PATH.rindex('\\')]
sys.path.append(PKG_PATH)

from db_interface import db_interface
from scipy import stats
from public_func.exchange_date import cal_stock_exchange_date
import datetime
from a_hold_stock_buy import stock_mkv_data
import math
from find_grow_chance import  scope_condition_company, stock_roe_rank
import csv


## 成交量扩大，短期上涨（时机、绩优）

def stock_turnover_rank():
    start, end = cal_stock_exchange_date(17)  ## 17天成交量
    print(start, end)
    sql_stock = f"select code, name, date, now, volume from stock_days_sh " \
                f"where date between '{start}' and '{end}' " \
             f"union " \
             f"select code, name, date, now, volume from stock_days_sz where date between '{start}' and '{end}' " \
             f"order by code asc, date desc"
    stock_data = db_interface.stock_base.select(sql_stock)
    vol_dict = {}
    for item in stock_data:
        code, name, date, price, volume = item
        if code[:2] not in ('20', '68'):  ## B股和科创股票
            date = date.strftime("%Y-%m-%d")
            if code not in vol_dict:
                vol_dict[code] = []
            vol_dict[code].append((
                code, name, date, price, volume
            ))

    res = []
    mkv_dict = stock_mkv_data(mkv=50)
    for k, v in vol_dict.items():
        vol_pct = [(round(v[i][4]/v[i+1][4], 2), v[i][2]) for i in range(len(v)-1) if v[i][4]/v[i+1][4] >= 1.20]
        vol_sum = sum([x[0] for x in vol_pct])
        if k in mkv_dict:
            mkv_data = mkv_dict[k]
            res.append({
                "vol_sum": round(vol_sum, 2),
                "code": k,
                "name": mkv_data[0],
                "mkv": mkv_data[1],
                "pct": vol_pct,
            })
    print('=============')
    result = sorted(res, key=lambda x: x["vol_sum"], reverse=True)
    all_stock = scope_condition_company(ids='')
    basic_stock = stock_roe_rank(scope_dict=all_stock)[:500]  ## 前500的绩优股
    basic_dict = dict([(x['code'], x) for x in basic_stock])
    turnover_res = []
    for i, item in enumerate(result[:200]):
        code = item['code']
        if code in basic_dict:
            basic_data = basic_dict[code]
            item.update(basic_data)
            print(i+1, item,)
            print()
            turnover_res.append(item)

    return




if __name__ == "__main__":
    stock_turnover_rank()  ## 短期成交量高，业绩好。
